package com.asuka.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.asuka.constant.MessageConstant;
import com.asuka.context.BaseContext;
import com.asuka.dto.OrderPageDTO;
import com.asuka.dto.OrderPayDTO;
import com.asuka.dto.OrderSearchDTO;
import com.asuka.dto.OrdersSubmitDTO;
import com.asuka.entity.*;
import com.asuka.exception.AddressBookBusinessException;
import com.asuka.exception.OrderBusinessException;
import com.asuka.exception.ShoppingCartBusinessException;
import com.asuka.mapper.*;
import com.asuka.result.PageResult;
import com.asuka.result.Result;
import com.asuka.service.OrderService;
import com.asuka.utils.HttpClientUtil;
import com.asuka.vo.OrderSubmitVO;
import com.asuka.vo.OrderVO;
import com.asuka.vo.OrderStatisticsVO;
import com.asuka.vo.WebSocketRemindVO;
import com.asuka.websocket.WebSocketService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WebSocketService webSocketService;


    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;



    @Override
    @Transient
    public OrderSubmitVO OrderController(OrdersSubmitDTO ordersSubmitDTO) {

        //判断地址是否为空
        AddressBook address = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if(address == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //checkOutOfRange(address.getCityName()+address.getDistrictName()+address.getDetail());

        //获得购物车数据,判断是否为空
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(BaseContext.getCurrentId())
                .build();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(shoppingCart);

        if(shoppingCarts == null || shoppingCarts.isEmpty()){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        //想订单表插入数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);

        //设置order参数
        order.setUserId(BaseContext.getCurrentId());
        order.setOrderTime(LocalDateTime.now()); //下单时间

        order.setPhone(address.getPhone());
        order.setAddress(address.getDetail());
        order.setConsignee(address.getConsignee()); //收货人


        //查询用户
        //User user = userMapper.selectById(address.getUserId());
        //order.setUserName(user.getName());

        order.setPayStatus(Orders.UN_PAID);
        order.setStatus(Orders.PENDING_PAYMENT);  //订单状态

        //用时间戳和userid当作订单号
        order.setNumber(String.valueOf(System.currentTimeMillis()) + address.getUserId()); //订单号


        //插入数据
        orderMapper.insert(order);

        //插入n条订单详细表
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shopping : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shopping,orderDetail);
            orderDetail.setOrderId(order.getId());

            orderDetailList.add(orderDetail);
        }


        orderDetailMapper.insertList(orderDetailList);

        //清空购物车
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());

        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();


        return orderSubmitVO;
    }


    @Override
    public Orders pay(OrderPayDTO orderPayDTO) {
        Orders order = Orders.builder()
                .number(orderPayDTO.getOrderNumber())
                .payMethod(orderPayDTO.getPayMethod())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        //.estimatedDeliveryTime(LocalDateTime.now().plusHours(1))
        //LocalDateTime now = LocalDateTime.now().plusHours(1);

        orderMapper.updateByNumber(order);

        return order;
    }


    @Override
    public PageResult selectPageList(OrderPageDTO page) {
        PageHelper.startPage(page.getPage(),page.getPageSize());

        Orders order = Orders.builder()
                .userId(BaseContext.getCurrentId())
                .status(page.getStatus())
                .build();

        Page<OrderVO> list = (Page<OrderVO>) orderMapper.selectList(order);

        for (OrderVO orderVO : list.getResult()) {
            List<OrderDetail> odList = orderDetailMapper.selectByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(odList);
        }


        return new PageResult(list.getTotal(),list.getResult());
    }


    @Override
    public OrderVO details(Long id) {
        Orders order = Orders.builder()
                .id(id)
                .build();

        //查询order
        Orders orders = orderMapper.selectById(id);

        OrderVO vo = new OrderVO();
        BeanUtils.copyProperties(orders,vo);

        //查询订单详细表
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(id);
        vo.setOrderDetailList(orderDetailList);


        return vo;
    }

    @Override
    public void cancel(Long id) {
        Orders order = Orders.builder()
                .id(id)
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .build();

        orderMapper.updateById(order);
    }


    @Override
    public void repetition(Long id) {
        //查询当前订单的订单详细表
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(id);

        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        //将当前订单详细表添加到list
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);

            //设置必要参数
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());


            shoppingCartList.add(shoppingCart);
        }

        //添加到购物车
        shoppingCartMapper.insertList(shoppingCartList);

    }

    @Override
    public PageResult search(OrderSearchDTO orderSearchDTO) {
        PageHelper.startPage(orderSearchDTO.getPage(),orderSearchDTO.getPageSize());


        Page<Orders> page = (Page<Orders>) orderMapper.search(orderSearchDTO);

        return new PageResult(page.getTotal(),page.getResult());
    }


    @Override
    public OrderStatisticsVO statistics() {

        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);

        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                .deliveryInProgress(deliveryInProgress)
                .confirmed(confirmed)
                .toBeConfirmed(toBeConfirmed)
                .build();

        return orderStatisticsVO;
    }

    @Override
    public void confirm(Orders order) {
        order.setStatus(Orders.CONFIRMED);
        orderMapper.updateById(order);

    }

    @Override
    @Transient
    public void rejection(Orders order) {

        Orders orders = Orders.builder()
                .id(order.getId()).build();

        Orders o = orderMapper.selectById(orders.getId());


        if(o.getPayStatus().equals(Orders.PAID)){
            //如果已经支付的订单   退款
            log.info("退款,{}",o.getAmount());
            order.setPayStatus(Orders.REFUND);
        }
        //设置订单信息 更新
        order.setStatus(Orders.CANCELLED);

        order.setCancelTime(LocalDateTime.now());

        orderMapper.updateById(order);
    }

    @Override
    @Transient
    public void adminCancel(Orders order) {

        Orders orders = Orders.builder()
                .id(order.getId()).build();

        Orders o = orderMapper.selectById(orders.getId());

        if(o.getPayStatus().equals(Orders.PAID)){
            //如果已经支付的订单   退款
            log.info("退款,{}",o.getAmount());
            order.setPayStatus(Orders.REFUND);
        }

        //设置订单信息 更新
        order.setStatus(Orders.CANCELLED);

        order.setCancelTime(LocalDateTime.now());

        orderMapper.updateById(order);
    }


    @Override
    public void delivery(Long id) {

        Orders orders = orderMapper.selectById(id);

        if(orders == null || !orders.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders order = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();

        orderMapper.updateById(order);

    }


    @Override
    public void reminder(Long id) {

        Orders orders = orderMapper.selectById(id);

        if(orders == null && !orders.getPayStatus().equals(Orders.PAID)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        WebSocketRemindVO webSocketRemindVO = WebSocketRemindVO.builder()
                .orderId(id)
                .type(WebSocketRemindVO.REMINDER)
                .content("用户催单")
                .build();

        webSocketService.sendToAllClient(webSocketRemindVO);
    }

    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.selectById(id);

        if(orders == null || !orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders order = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();

        orderMapper.updateById(order);
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }
}
